package com.study.demo.aop.demo1_2.parser;

import com.study.demo.aop.demo1_2.annotation.Logable;
import com.study.demo.aop.demo1_2.operation.LogOperation;
import com.study.demo.aop.demo1_2.operation.LogableOperation;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.lang.Nullable;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author: elvin
 * @time: 2019-10-16 15:06
 * @desc:
 **/
public class SpringLogAnnotationParser implements LogAnnotationParser, Serializable {
    @Override
    public LogOperation parseLogAnnotations(Class<?> type) {
        return doParseLogAnnotations(type);
    }

    @Override
    public LogOperation parseLogAnnotations(Method method) {
        return doParseLogAnnotations(method);
    }

    private LogOperation doParseLogAnnotations(AnnotatedElement ae) {
        Collection<Logable> annos = AnnotatedElementUtils.getAllMergedAnnotations(ae, Logable.class);
        if (!annos.isEmpty()) {
            for (Logable logable : annos) {
                return parseLogableAnnotation(ae, logable);
            }
        }
        return null;
    }

    LogOperation parseLogableAnnotation(AnnotatedElement ae, Logable logable) {
        LogableOperation.Builder builder = new LogableOperation.Builder();
        builder.setCondition(logable.condition());
        builder.setUnless(logable.unless());

        LogOperation op = builder.build();
        //validateLogOperation(ae, op);
        return op;
    }

    //此处暂无需要验证
    /*private void validateLogOperation(AnnotatedElement ae, LogOperation operation) {

    }*/
}
